<template>
  <section class="cms-page">
    <h2 class="cms-title">{{edit_type}}服务类别</h2>
    <el-form
      v-loading="loading"
      class="cms-form"
      ref="form"
      :model="form" label-width="80px">
      <el-form-item
        label="类别名称："
        prop="name"
        :rules="[{required: true, message: '请输入服务类别名称' }]"
      >
        <el-input v-model="form.name" placeholder="请输入服务类别名称"></el-input>
      </el-form-item>
      <el-form-item
        label="描述："
        prop="des"
        :rules="[{required: true, message: '请输入服务类别描述' }]"
      >
        <el-input type="textarea" autosize v-model="form.des" placeholder="请输入服务类别描述"></el-input>
      </el-form-item>
      <el-form-item
        label=" "
      >
       <el-button
         @click="ensure"
         :disabled="disabled"
         :loading="submit_loading"
         type="primary">确定</el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script>
  /**
   * @Author: lifuzhao
   * @Date: 2019-05-15
   * @Project: eabax
   */
  export default {
    name: 'edit',
    data() {
      return {
        loading: false,
        submit_loading: false,
        form: {
          name: '',
          des: ''
        }
      }
    },
    computed: {
      edit_type() {
        let query = this.$route.query
        return query.id ? '编辑' : '新增'
      },
      disabled(){
        let form = this.form
        return !form.name || !form.des
      }
    },
    watch: {
      $route: {
        deep: true,
        handler() {
          this.init()
        }
      }
    },
    mounted(){
      this.init()
    },
    methods: {
      init() {
        let query = this.$route.query
        if (query.id) {
          this.form = query
        }
      },
      ensure(){
        let form = this.form,
          disabled = this.disabled,
          edit_type = this.edit_type,
          url = '/api/v1/category'
        if(disabled) return
        this.submit_loading = true
        if(form.id){
          url = '/api/v1/category/update'
        }
        this.$axios
          .$post(url, form)
          .then(res => {
            this.submit_loading = false
            this.$message({
              message: edit_type + '成功',
              type: 'success'
            })
            this.$router.push({
              path: '/cms/home'
            })
          })
          .catch(res => {
            this.$message({
              message: edit_type + '失败',
              type: 'error'
            })
            this.submit_loading = false
          })
      }
    },
    layout: 'cms'
  }
</script>